#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/7 23:47
# @file     : __init__.py
# @Software : PyCharm
# ======================================#

import datetime
import functools
import json
import os

import flask
from flask import jsonify
from flask import request, session
from flask_cors import CORS

from apps.client.redis_client import Redis
from apps.config import SECRET_KEY
# Json 无法解析 datatime 类型的数据，构建 DateEncoder 类解决 datatime 解析问题
from apps.models.logger import log
# Json 无法解析 datatime 类型的数据，构建 DateEncoder 类解决 datatime 解析问题
from apps.models.table_crud import query_table


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


json.dumps = functools.partial(json.dumps, cls=DateEncoder)


def check_token(token):
    if not token:
        return False
    exists = Redis.get(token)
    if exists is None:
        table = "private_key"
        where = {"private_key": token, "status": "1"}
        result = query_table(table, where=where, fetchone=True)
        if result.get("status"):
            data = result.get("data")
            if data and data.get("private_key") == token:
                Redis.set(token, 1, expire=28800)
                return True
            else:
                Redis.set(token, 0, expire=7200)
                return False
    elif exists == "1":
        return True
    else:
        return False


def create_app(config=None):
    app = flask.Flask(__name__)
    # 支持全局跨域
    CORS(app)
    # load default configuration
    app.config.from_object('apps.settings')
    # load environment configuration
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')
    # load apps sepcified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    app.config['SECRET_KEY'] = SECRET_KEY
    app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(hours=1)
    from apps import auth, models, api

    from apps import auth, models

    # auth.init_app(app)
    with app.app_context():
        models.init_app(app)
    auth.init_app(app)
    api.init_app(app)

    @app.route("/health")
    def health():
        return jsonify("I am OK!")

    @app.before_request
    def before_request():
        if request.path == "/api/v1/login" or request.path.endswith(".js") or request.path.endswith(".css"):
            pass
        else:
            private_token = request.cookies.get("token")
            if check_token(private_token):
                pass
            else:
                username = request.cookies.get("SessionId")
                role = request.cookies.get("role")
                email = session.get('username')
                if username is None or username != email:
                    info = {
                        "status": False,
                        "msg": "no login!",
                    }
                    return jsonify(info)
                if role is None or role != session.get("role"):
                    info = {
                        "status": False,
                        "msg": "please use right role!",
                    }
                    return jsonify(info)

    return app


if __name__ == '__main__':
    app = create_app()
    app.run(host='localhost', port=5000, debug=True)
